import 'dart:async';
import 'dart:convert';
import 'dart:math';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:wanxiang_app/bean/normal_entity.dart';
import 'package:wanxiang_app/bean/qa_list_entity.dart';
import 'package:wanxiang_app/pages/home/detail.dart';
import 'package:wanxiang_app/pages/home/qaDetail.dart';
import 'package:wanxiang_app/utils/common.dart';
import 'package:wanxiang_app/utils/constant.dart';
import 'package:wanxiang_app/utils/user_util.dart';
import 'package:wanxiang_app/widgets/account_textField2.dart';
import '../../bean/goods_detail_entity.dart';
import '../../bean/login_entity.dart';
import '../../bean/msg_new_service_entity.dart';
import '../../bean/service_list_entity.dart';
import '../../utils/network_manager.dart';
import '../../utils/network_url.dart';
import '../../utils/toast_util.dart';
import '../../widgets/NoShadowScrollBehavior.dart';
import '../../widgets/chatAppbar.dart';
import '../../widgets/img_dialog.dart';
import '../../widgets/myappbar.dart';
import 'package:get/get.dart';
import 'package:easy_refresh/easy_refresh.dart';

import 'package:emoji_picker_flutter/emoji_picker_flutter.dart';
import 'package:flutter/foundation.dart' as foundation;
import 'package:nim_core/nim_core.dart';
import 'package:image_picker/image_picker.dart';
import 'package:bot_toast/bot_toast.dart';

import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';

class ChatController extends GetxController {
   GoodsDetailData? detailData;
  @override
  void onInit() {
    super.onInit();
    // _getService();
    Map map = Get.arguments;
    // if(map['online']!=null){
    //   online = map['online'];
    // }
    sessionId = map['sessionId'];
    nickName = map['nickName'];
    servicePhoto = map['servicePhoto'];
    myId = UserUtil.getUSER()!.userName.toString();
    if(map['info']!=null){
      detailData = map['info'];
    }

    isFirst = true;
    getCreateEmpty();
    _getServices();
    _addListener();
    update();
  }
   void _getServices() {
     DioManager.getInstance().getRequest2(ServiceUrl.getImByAccount, {},
             (data) async {
           var parsedJson = json.decode(data);
           MsgNewServiceEntity bannerEntity =
           MsgNewServiceEntity.fromJson(jsonDecode(parsedJson));
           for(var item in bannerEntity.data){
             if(item.nickname.toString() == nickName){
                 online = item.isRest;
                  break;
             }
           }
         }, (error) {
           ToastUtil.show(error);
         });
   }

  getCreateEmpty() async{
    NIMResult<NIMMessage> result1 = await MessageBuilder.createEmptyMessage(
        sessionId: sessionId, sessionType: NIMSessionType.p2p, timestamp: DateTime.now().millisecondsSinceEpoch);
    _getRecent(result1.data,true);
  }

  @override
  void onClose() {
    super.onClose();
    subsriptions?.cancel();
  }
  bool isFirst = false;
  String myId = '';
  String nickName = '';
  String sessionId= '';
  int  online = 0;
  String servicePhoto = '';
  List<QaListData> list = [];
  bool emojiShowing = false;
  late LoginData serviceData;
  final ScrollController _scrollController = ScrollController();

  List<NIMMessage> recentList = [];
  _getRecent(NIMMessage? data,bool isFirst) async{
    /// 从本地消息数据库搜索消息历史。
    /// 搜索将返回：时间在 (startTime,endTime) 之间，消息类型为指定类型，且匹配搜索内容或消息发起者列表的一定数量的消息。
    ///
    ///  [sessionType] 会话类型
    ///  [sessionId] 聊天对象ID
    ///  [option] 搜索选项
    ///

    // NIMResult<NIMMessage> result1 = await MessageBuilder.createEmptyMessage(
    //     sessionId: sessionId, sessionType: NIMSessionType.p2p, timestamp: DateTime.now().millisecondsSinceEpoch);

    /// 查询比 anchor时间更早的消息，查询20条，结果按照时间降序排列
    // NIMResult<List<NIMMessage>> result = await NimCore.instance.messageService.queryMessageListEx(result1.data!,QueryDirection.QUERY_OLD,30);

    int? newTime = data?.timestamp;
    int oldTime = newTime! - 1000 * 60 * 60*24*30; // 1月前
    List<NIMMessageType> typeList = [];
    typeList.add(NIMMessageType.text);
    typeList.add(NIMMessageType.image);
    typeList.add(NIMMessageType.custom);
    NIMResult<List<NIMMessage>> result = await NimCore.instance.messageService.pullMessageHistoryExType(data!,oldTime,100,QueryDirection.QUERY_OLD,typeList,true);
    if(result.data!.length>0 && result.data?[0].uuid.toString() != data.uuid.toString()){
      recentList = [...?result.data,...recentList];
      if(isFirst) {
      }

      update();
    }
    print('recentList===='+recentList.length.toString());
    if(isFirst){
      // Timer(const Duration(milliseconds: 1200),
      //         () => _scrollController.animateTo(_scrollController.position.maxScrollExtent+550.h, duration: const Duration(milliseconds: 500), curve: Curves.linear));
      Future.delayed(Duration(milliseconds: 500), () {
        _scrollController.jumpTo(0.0);
      });

      _clearMsg();

    }

  }

   String _getDate(timeStamp){
    DateTime dateTime = DateTime.fromMillisecondsSinceEpoch(timeStamp);
    DateTime dateTimeNow =DateTime.now();
    if(dateTimeNow.day!=dateTime.day){
      return '${dateTime.month<10?'0${dateTime.month}':dateTime.month }-${dateTime.day<10?'0${dateTime.day}':dateTime.day} ${dateTime.hour<10?'0${dateTime.hour}':dateTime.hour}:${dateTime.minute<10?'0${dateTime.minute}':dateTime.minute}';
      // return '${dateTime.month}-${dateTime.day} ${dateTime.hour}:${dateTime.minute}';
    }
    return '${dateTime.hour<10?'0${dateTime.hour}':dateTime.hour}:${dateTime.minute<10?'0${dateTime.minute}':dateTime.minute}';

  }


  _clearMsg() async{
    List<NIMSessionInfo> sss= [];
    NIMSessionInfo nimSessionInfo = NIMSessionInfo(sessionId: sessionId, sessionType: NIMSessionType.p2p);
    sss.add(nimSessionInfo);
    NIMResult<List<NIMSessionInfo>> result = await  NimCore.instance.messageService.clearSessionUnreadCount(sss);
  }

  _sendTextMsg(String text){
    if(text.isEmpty){
      return;
    }
    // 该帐号为示例
    String? account = UserUtil.getUSER()?.mobile;
// 以单聊类型为例
    NIMSessionType sessionType = NIMSessionType.p2p;
// 创建并且发送一个文本消息

    MessageBuilder.createTextMessage(
        sessionId: sessionId, sessionType: sessionType, text: text
    ).then<NIMResult>((result) {
      if (result.isSuccess) {
        result.data!.config = NIMCustomMessageConfig(enablePush: true,enableUnreadCount: true);
        result.data!.pushPayload = {"pushTitle":UserUtil.getUSER()?.nickname,};
        recentList.insert(0, result.data!);
        // _scrollController.jumpTo(0.0);

        return NimCore.instance.messageService
            .sendMessage(message: result.data!);
      } else {
        return result;
      }
    }).then((result) {
      detailData = null;
      print(
          'MessageService##send message: ${result.code} ${result.errorDetails}');
      _clearMsg();
    });
    update();
  }

  _sendCustomerMsg(){
    Map<String,dynamic> map ={
      'img_url':detailData?.imgUrl,
      'price':detailData?.sellPrice,
      'link':"http://103.26.77.113:10000/zmobile/show.aspx?gid="+detailData!.channelId.toString()+'&id='+detailData!.id.toString(),
      'id':detailData?.channelId.toString(),
      'title':detailData?.title,
      'channelName':detailData!.channelName,
      'gId':detailData!.id.toString(),
      'gName':detailData!.goodName
    };

    NIMCustomMessageAttachment attachment =NIMCustomMessageAttachment(data: map);
    detailData = null;
    MessageBuilder.createCustomMessage(  sessionId: sessionId,
      sessionType: NIMSessionType.p2p,
      attachment: attachment
    ).then<NIMResult>((result) {
      if (result.isSuccess) {
        result.data!.pushPayload = {"pushTitle":UserUtil.getUSER()?.nickname,};
        result.data!.config = NIMCustomMessageConfig(enablePush: true,enableUnreadCount: true);
        recentList.insert(0, result.data!);
        _scrollController.jumpTo(0.0);
        update();
        return NimCore.instance.messageService
            .sendMessage(message: result.data!);
      } else {
        return result;
      }
    }).then((result) {
      detailData = null;
      _clearMsg();
      print(
          'MessageService##send message: ${result.code} ${result.errorDetails}');
    });
  }

  _sendImageMsg(String path){
    if(path.isEmpty){
      return;
    }
    // 该帐号为示例
    String? account = UserUtil.getUSER()?.mobile;
// 以单聊类型为例
    NIMSessionType sessionType = NIMSessionType.p2p;
    MessageBuilder.createImageMessage(
      sessionId: sessionId,
      sessionType: NIMSessionType.p2p,
      filePath: path,
      fileSize: 0,
      displayName: 'image',
    ).then<NIMResult>((result) {
      if (result.isSuccess) {
      //   recentList.add(result.data!);
      // update();
        result.data!.pushPayload = {"pushTitle":UserUtil.getUSER()?.nickname,};
        result.data!.config = NIMCustomMessageConfig(enablePush: true,enableUnreadCount: true);
        BotToast.showLoading();
        Future<NIMResult<NIMMessage>> ff= NimCore.instance.messageService
            .sendMessage(message: result.data!);
        ff.then((value) => {
        BotToast.closeAllLoading(),
          recentList.insert(0, value.data!),
          _scrollController.jumpTo(0.0),
            update(),
        // Timer(Duration(milliseconds: 500),
        // () => _scrollController.animateTo(_scrollController.position.maxScrollExtent+400.h, duration: Duration(milliseconds: 500), curve: Curves.linear))
        });
        _clearMsg();
        return ff;
      } else {
        return result;
      }
    }).then((result) {
    });

  }
   StreamSubscription? subsriptions ;
  _addListener(){
    subsriptions = NimCore.instance.messageService.onMessage.listen((messages) {
      List<NIMMessage> aa = [];
      for(var item in messages){
        if(item.sessionId == sessionId){
          aa.add(item);
        }
      }
           recentList.insertAll(0,aa);
            _clearMsg();

      update();

            // _scrollController.jumpTo(0.0);
    });
  }
  _emojText(String text){
    text.runes.forEach((rune) {
      String str = new String.fromCharCode(rune);
    });
  }

   EasyRefreshController easyRefreshController = EasyRefreshController(
     controlFinishRefresh: true,
     controlFinishLoad: false,
   );
bool isFirstRefresh = true;
}

class ChatPage extends GetView<ChatController> {
  late ChatController controller;

  late BuildContext context;

  @override
  Widget build(BuildContext context1) {
    Get.lazyPut<ChatController>(() => ChatController());

    controller = Get.find();
    context = context1;
    if(controller.isFirst && controller.detailData!=null){

      Future.delayed(Duration(milliseconds: 500), () {
        _showGoodsDialog();
      });


    }
    return GetBuilder<ChatController>(
      builder: (_) {
        return Scaffold(
            appBar: ChatAppBar(
              context: context,
              title: controller.nickName,
              online: controller.online,
              hasLeading: true,
            ),
            backgroundColor: const Color(0xfff7f8fc),
            body:  _content());
      },
    );
  }



  Widget _content() {
    return GestureDetector(
      onTap: (){
        FocusScope.of(context).unfocus();
      },
      child: Container(
        height: Get.height,
        child: Stack(children: [
          // ScrollConfiguration(
          //   behavior: NoShadowScrollBehavior(),
          //   child: SingleChildScrollView(
          //     physics: ClampingScrollPhysics(),
          //       controller: controller._scrollController,
          //       child:  Container(
          //           width: Get.width,
          //           margin: EdgeInsets.only(bottom: 120.h),
          //           child: Column(
          //             children:_all(),
          //           )
          //       )
          //   ),
          // )
          Container(
              width: Get.width,
              margin: EdgeInsets.only(bottom: 80.h),
            child:  EasyRefresh(
              header: ClassicHeader(
                dragText: 'Release ready'.tr,
                armedText: 'Release ready'.tr,
                readyText: 'Refreshing...'.tr,
                processingText: 'Refreshing...'.tr,
                processedText: 'Succeeded'.tr,
                noMoreText: 'No more'.tr,
                failedText: 'Failed'.tr,
                messageText: 'Last updated at %T'.tr,
              ),
              footer: NotLoadFooter(),
              controller: controller.easyRefreshController,
              onRefresh: () async {
                if(controller.isFirstRefresh){
                  print('onRefreshonRefreshonRefresh111');
                  controller.isFirstRefresh = false;
                  controller.easyRefreshController.finishRefresh(
                      IndicatorResult.success );
                }else{
                  print('onRefreshonRefreshonRefresh222');
                  controller.easyRefreshController.finishRefresh(
                      IndicatorResult.success );
                }
                // controller._getRecent(controller.recentList[0],false);
              },
              onLoad: () async {


                if(controller.isFirstRefresh){
                  print('onLoadonLoadonLoad111');
                  controller.isFirstRefresh = false;
                  controller.easyRefreshController.finishLoad( IndicatorResult.success
                  );
                }else{
                  print('onLoadonLoadonLoad222');
                  controller.easyRefreshController.finishLoad( IndicatorResult.success );
                  controller._getRecent(controller.recentList[0],false);
                }

                //
                // controller.easyRefreshController.finishLoad(
                //     IndicatorResult.none );
              },
              child: ListView.builder(
                // controller: controller._scrollController,
                reverse: true,
                shrinkWrap:true,
                itemBuilder: (context, index) {
                  if(controller.recentList[index].sessionId=='000'){
                    return _goodsInfo();
                  }
                  else if(controller.recentList[index].fromAccount==controller.myId){
                    return _right(controller.recentList[index]);
                  }else{
                    return _left(controller.recentList[index]);
                  }
                }, itemCount: controller.recentList.length,
              ),
            )
          )
          ,
          Positioned(bottom: 0, child: _bottom())
        ])
      )
    ) ;
  }

  List<Widget> _all(){
    List<Widget> aa = [];
    for(var item in controller.recentList){
      if(item.fromAccount==controller.myId){
        aa.add(_right(item));
      }else{
        aa.add(_left(item));
      }
    }
    if(controller.detailData!=null){
      aa.add(_goodsInfo());
    }
    return aa;
  }

  Widget _left(NIMMessage msg) {
    return Container(
      margin: EdgeInsets.only(top: 10.h),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              ClipOval(
                 child: Image.network(

             controller. servicePhoto,
      width: 50.w,
      height: 50.w,
                   fit: BoxFit.cover,
    ),
              ),
              Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      SizedBox(
                        width: 5.w,
                      ),
                      Text(
                        controller.nickName,
                        style: TextStyle(
                            color: Color(0xFF666666),
                            fontWeight: FontWeight.bold,
                            fontSize: 14.sp),
                      ),
                      SizedBox(
                        width: 2.w,
                      ),
                      Image.asset(
                        Constant.IMG_BASE + 'gov.png',
                        width: 26.w,
                        height: 13.h,
                      ),
                      Container(
                          margin: EdgeInsets.only(left: 5.w, ),
                          child: Text(controller._getDate(msg.timestamp),style:TextStyle(
                              fontSize: 12.sp
                          ) )),
                    ],
                  ),

                  Container(
                    padding: EdgeInsets.all(10.w),
                    decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(5.r)),
                    child: ConstrainedBox(
                        constraints: BoxConstraints(
                          maxWidth: 200.w,
                        ),
                        child:_msg(msg,true)),
                  )


                ],
              ),

            ],
          ),

        ],
      ),
    );
  }

  Widget _gallery(url,context1){
    return    Container(
      height: Get.height - 30.h,
      child: Material(
          type: MaterialType.transparency,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              InkWell(
                onTap: (){
                  Navigator.of(context1).pop();
                },
                child:  Container(
                    height:  Get.height - 30.h,
                    width: Get.width,
                    child: PhotoViewGallery.builder(
                      scrollPhysics: const BouncingScrollPhysics(),
                      builder: (BuildContext context, int index) {
                        return PhotoViewGalleryPageOptions(
                          imageProvider: NetworkImage(Common.realPicPath(url) ),
                          initialScale: PhotoViewComputedScale.contained * 0.8,
                          heroAttributes: PhotoViewHeroAttributes(tag: 'imgs'),
                        );
                      },
                      itemCount: 1,
                      backgroundDecoration:  BoxDecoration(color: Colors.black12),
                    )
                )
              )
             ,

            ],
          )
      )  ,
    ) ;
  }


  _showGoodsDialog(){
    showDialog(
        context: context,

        builder: (context1) {
          return  _goodsWidget();
        });
  }

  Widget _goodsWidget(){
    return   controller.detailData==null?Container():
    Material(
        type: MaterialType.transparency,
    child: Container(
        alignment: Alignment.center,
      child: Container(
        height: 180.h,
        padding: EdgeInsets.all(10.w),
        margin: EdgeInsets.all(20.w),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(8.r),
          color: Colors.white
        ),
        child: Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                IconButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  icon: const Icon(
                    Icons.close,
                    size: 28,
                  ),
                ),
              ],
            ),

            Container(
                width: Get.width - 50.w,
                child:  Row(
                  children: [
                    Column(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Container(
                            width: Get.width - 50.w - 100.w - 40.w,
                            child: Text(controller.detailData!.title,
                              style: TextStyle(color: Color(0xFF333333),fontSize: 14.sp,),maxLines: 2,    textAlign: TextAlign.left,
                              overflow: TextOverflow.ellipsis,)
                        )
                        ,
                        Row(
                          children: [
                            Text('¥',style: TextStyle(color: Color(0xFFFF0000),fontSize: 12.sp),),
                            Text(controller.detailData!.sellPrice,style: TextStyle(color: Color(0xFFFF0000),fontSize: 16.sp,fontWeight: FontWeight.bold),),
                          ],
                        )
                      ],
                    ),
                    SizedBox(width: 10.w,),
                    Container(
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(5.r)
                      ),
                      child:  Image.network(Common.realPicPath(controller.detailData!.imgUrl) ,width: 120.w,height: 80.h,fit: BoxFit.cover,),
                    )

                  ],
                )
            ),
            Container(height: 0.5.h,color: Colors.grey,margin: EdgeInsets.only(top: 10.h,bottom: 10.h),),
            InkWell(
                onTap: (){

                  Navigator.of(context).pop();
                  controller._sendCustomerMsg();
                },
                child:  Text('发送商品',style: TextStyle(
                    color: Color(0x0FF007BE5),
                    fontSize: 16.sp
                ),)
            )

          ],

        ),
      )
    )
    )

 ;;
  }


  Widget _emojH5(String text,bool isLeft){
    String aa = text.substring(1,text.length-1);
    if(aa.startsWith('ajmd')){
      return    Image.asset(
        Constant.IMG_BASE + 'emoj/ajmd/'+aa+'.png',
      );
    }
    else if(aa.startsWith('arclist')){
      return    Image.asset(
        Constant.IMG_BASE + 'emoj/arclist/'+aa+'.png',
      );
    } else if(aa.startsWith('lt')){
      return    Image.asset(
        Constant.IMG_BASE + 'emoj/lt/'+aa+'.png',
      );
    }else if(aa.startsWith('xxy')){
      return    Image.asset(
        Constant.IMG_BASE + 'emoj/xxy/'+aa+'.png',
      );
    }
    else{

      String cc = Common.emoji[text]['file'];
      return    Image.asset(
        Constant.IMG_BASE + 'emoj/emoji/'+cc,
      );
    }

  }

  Widget _msg(NIMMessage msg,bool isLeft){
    if(msg.messageType == NIMMessageType.text){
      if(msg.content!.startsWith('[')){
        return _emojH5( msg.content!,isLeft);
      }else{
        return SelectableText(
          msg.content!,
          style: TextStyle(color:isLeft?Colors.black:Colors.white),
        );
      }

    }
    if(msg.messageType == NIMMessageType.image){
      if(msg.messageAttachment==null || (msg.messageAttachment?.toMap())?['thumbUrl']==null){
        return Container();
      }
     return
       InkWell(
         onTap: (){
           // showDialog(context: context, builder: (BuildContext context1) {
           //   return MyPhotoDialog(url: (msg.messageAttachment?.toMap())?['url'],
           //   );
           // });

           showDialog(
               context: context,

               builder: (context1) {
                 return  _gallery(msg.messageAttachment?.toMap()?['url'],context1);
               });

         },
         child: Image.network((msg.messageAttachment?.toMap())?['thumbUrl'],fit: BoxFit.contain,)
       );

    }
    if(msg.messageType == NIMMessageType.custom){
      if(msg.messageAttachment==null){
        return Container();
      }
      NIMCustomMessageAttachment attachment = msg.messageAttachment as NIMCustomMessageAttachment;
      Map? map = {};
      if(attachment.data?['data']  == null){
        map = attachment.data;
      }else{
        map =attachment.data?['data'] ;
      }
      return InkWell(
        onTap: (){
          // 'id':detailData?.id.toString(),
          // 'title':detailData?.title,
          // 'channelName':detailData!.channelName,
          // 'gName':detailData!.goodName

          Get.to(()=>DetailPage(),arguments: {
            "title":map?['gName'],
            "record_id":'',
            "channel_name":map?['channelName'],
            "goods_id":map?['gId'],
          },preventDuplicates:false);
        },
        child: Container(
          width: 250.w,
          child: Row(
            children: [
              ClipRRect(
                  borderRadius: BorderRadius.circular(5.r),
                child: Image.network(Common.realPicPath(map?['img_url']),width: 80.w,height: 60.h,fit: BoxFit.cover,)
              ) ,
              Container(
                  margin: EdgeInsets.only(left: 5.w),
                  width: 150.w,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(map?['title'],style: TextStyle(
                        overflow: TextOverflow.ellipsis,
                      ),maxLines: 3,),
                      Text('¥ '+map!['price'].toString(),style: TextStyle(
                          color: Color(0xFFEF3D4E)
                      ),),
                    ],
                  )
              )

            ],
          ),
        )
      ) ;
    }
    return Container();
  }


  Widget _right(NIMMessage msg) {
    return Container(
      margin: EdgeInsets.only(top: 10.h),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.end,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Column(
                mainAxisAlignment: MainAxisAlignment.end,
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Row(
                    children: [
                      Text(UserUtil.getUSER()!.nickname,style:  TextStyle(
                          color: Color(0xFF666666), fontWeight: FontWeight.bold,
                          fontSize: 14.sp
                      ),),
                      SizedBox(width: 2.w,),
                      Text(controller._getDate(msg.timestamp),style:  TextStyle(
                          fontSize: 12.sp
                      ),),
                    ],
                  ),
      Container(
      margin: EdgeInsets.only(top: 5.h),
        padding: EdgeInsets.all(10.w),
        decoration: BoxDecoration(
            color: msg.messageType == NIMMessageType.custom?Colors.white: Color(0xFF007BE5),
            borderRadius: BorderRadius.circular(5.r)),
        child: ConstrainedBox(
            constraints: BoxConstraints(
              maxWidth: 250.w,
            ),
            child:   _msg(msg,false))
    )
                ],
              ),

              SizedBox(width: 3.w,),
              Column(
                children: [

                  Container(
                      width: 50.w,
                      height: 50.w,
                      child:    ClipOval(
                          child:  Image.network(
                            UserUtil.getUSER()!.userPhoto,
                            width: 50.w,
                            height: 50.w,
                            fit: BoxFit.cover,
                          )
                      )
                  ),

                ],
              )


             ,
            ],
          ),

        ],
      ),
    );
  }

  Widget _goodsInfo(){
    return controller.detailData==null?Container():
    Container(
      padding: EdgeInsets.all(10.w),
      margin: EdgeInsets.all(20.w),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8.r),
        border: Border.all(color: Color(0xffdddee1),width: 1.w),
      ),
      child: Column(
        children: [
          Container(
            width: Get.width - 50.w,
            child:  Row(
              children: [
                Image.network(Common.realPicPath(controller.detailData!.imgUrl) ,width: 60.w,height: 60.h,fit: BoxFit.cover,),
                SizedBox(width: 10.w,),
                Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                        width: Get.width - 50.w - 100.w,
                      child: Text(controller.detailData!.title,
                        style: TextStyle(color: Color(0xFF333333),fontSize: 14.sp,),maxLines: 2,    textAlign: TextAlign.left,
                        overflow: TextOverflow.ellipsis,)
                    )
                    ,
                    Row(
                      children: [
                        Text('¥',style: TextStyle(color: Color(0xFFFF0000),fontSize: 12.sp),),
                        Text(controller.detailData!.sellPrice,style: TextStyle(color: Color(0xFFFF0000),fontSize: 16.sp),),
                      ],
                    )
                  ],
                )
              ],
            )
          ),
           Container(height: 0.5.h,color: Colors.grey,margin: EdgeInsets.only(top: 10.h,bottom: 10.h),),
           InkWell(
             onTap: (){
              controller._sendCustomerMsg();
             },
             child:  Text('发送商品',style: TextStyle(
                 color: Color(0xFF007BE5),
                 fontSize: 16.sp
             ),)
           )

        ],

      ),
    );
  }




  // Widget _buildInputTextComposer() {
  //   return Container(
  //       width: Get.width - 130.w-20.w - 12.w,
  //       child: TextField(
  //           style: const TextStyle(fontSize: 16),
  //           controller: _textController,
  //           maxLines: null,
  //         onTap: (){
  //             controller.emojiShowing = false;
  //             controller.update();
  //         },
  //           ));
  // }

  Widget _buildInputTextComposer() {
    return Container(
        width: Get.width - 130.w-20.w - 12.w,
        constraints: BoxConstraints(maxHeight: 80.h,),

        child: SingleChildScrollView(
            child: TextField(
              style: const TextStyle(fontSize: 16),
              controller: _textController,
              maxLines: null,
              onTap: (){
                controller.emojiShowing = false;
                controller.update();
              },
            )
        ) );
  }

  TextEditingController _textController =
      TextEditingController(); // 用来监听TextField的输入内容

  _onBackspacePressed() {
    _textController
      ..text = _textController.text.characters.toString()
      ..selection = TextSelection.fromPosition(
          TextPosition(offset: _textController.text.length));
  }

  Widget _bottom() {
    return Container(
      width: Get.width,
      height: controller.emojiShowing ? 310.h : 80.h,
      color: Colors.white,
      child: Column(
        children: [
          Row(
            children: [
              IconButton(
                onPressed: () {
                  FocusScope.of(context).unfocus();
                  controller.emojiShowing = !controller.emojiShowing;

                  controller.update();
                },
                icon: const Icon(
                  Icons.mood,
                  size: 28,
                ),
              ),
              _buildInputTextComposer(),
              IconButton(
                onPressed: () async{
                  FocusScope.of(context).unfocus();
                  final ImagePicker picker = ImagePicker();
                  final XFile? image = await picker.pickImage(source: ImageSource.gallery);
                  controller._sendImageMsg(image!.path);
                },
                icon: const Icon(
                  Icons.photo,
                  size: 28,
                ),
              ),
              InkWell(
                  onTap: () {
                   controller._sendTextMsg(_textController.text);
                   _textController.text= '';
                    FocusScope.of(context).unfocus();
                    controller.emojiShowing=false;
                   controller.update();
                  },
                  child: Container(
                    margin: EdgeInsets.only(right: 5.w),
                    decoration: const BoxDecoration(
                      color: Color(0xFF007BE5),
                    ),
                    alignment: Alignment.center,
                    width: 60.w,
                    height: 30.h,
                    child: const Text(
                      '发送',
                      style: TextStyle(color: Colors.white),
                    ),
                  ))
            ],
          ),
           controller.emojiShowing? SizedBox(
                  height: 250.h,
                  child: EmojiPicker(
                    textEditingController: _textController,
                    onBackspacePressed: _onBackspacePressed,
                    config: Config(
                      columns: 7,
                      emojiSizeMax: 32 *
                          (foundation.defaultTargetPlatform ==
                                  TargetPlatform.iOS
                              ? 1.30
                              : 1.0),
                      verticalSpacing: 0,
                      horizontalSpacing: 0,
                      gridPadding: EdgeInsets.zero,
                      initCategory: Category.RECENT,
                      bgColor: const Color(0xFFF2F2F2),
                      indicatorColor: Colors.blue,
                      iconColor: Colors.grey,
                      iconColorSelected: Colors.blue,
                      backspaceColor: Colors.blue,
                      skinToneDialogBgColor: Colors.white,
                      skinToneIndicatorColor: Colors.grey,
                      enableSkinTones: true,
                      recentTabBehavior: RecentTabBehavior.RECENT,
                      recentsLimit: 28,
                      replaceEmojiOnLimitExceed: false,
                      noRecents: const Text(
                        'No Recents',
                        style: TextStyle(fontSize: 20, color: Colors.black26),
                        textAlign: TextAlign.center,
                      ),
                      loadingIndicator: const SizedBox.shrink(),
                      tabIndicatorAnimDuration: kTabScrollDuration,
                      categoryIcons: const CategoryIcons(),
                      buttonMode: ButtonMode.MATERIAL,
                      checkPlatformCompatibility: true,
                    ),
                  )):Container(),
        ],
      ),
    );
  }
}
